package com.heima.behavior.service.impl;

import com.heima.behavior.model.dto.LikesBehaviorDto;
import com.heima.behavior.model.entity.ApLikesBehavior;
import com.heima.behavior.service.ApLikesBehaviorService;
import com.heima.behavior.util.AppUserThreadLocalUtil;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.user.entity.ApUser;
import org.bson.types.ObjectId;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Date;

@Service
public class ApLikesBehaviorServiceImpl implements ApLikesBehaviorService {

    @Resource
    private StringRedisTemplate stringRedisTemplate;

    @Resource
    private MongoTemplate mongoTemplate;

    @Override
    public ResponseResult like(LikesBehaviorDto dto) {
        //1. 校验参数
        if (dto.getArticleId() == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_REQUIRE);
        }
        ApUser user = AppUserThreadLocalUtil.get();
        if (user == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.NEED_LOGIN);
        }

        //2. 判断是否已经点赞
        String user_like_key = "USER_LIKE_" + dto.getArticleId();
        Boolean hasKey = stringRedisTemplate.opsForHash().hasKey(user_like_key, user.getId() + "");

        //2.1 已经点赞 - 再点赞  什么都不做
        if (hasKey && dto.getOperation() == 0) {
            return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
        }

        //2.2 已经点赞 - 取消赞  删除数据(redis数据, mongodb数据)
        if (hasKey && dto.getOperation() == 1) {
            //2.2.1 删除Redis数据
            stringRedisTemplate.opsForHash().delete(user_like_key, user.getId() + "");

            //2.2.2 删除MongoDB数据
            Query query = Query.query(Criteria.where("userId").is(user.getId()).and("articleId").is(dto.getArticleId()));
            mongoTemplate.remove(query, ApLikesBehavior.class);
        }

        //2.3 没有点赞 - 点赞  保存数据(redis数据, mongodb数据)
        if (!hasKey && dto.getOperation() == 0) {
            //2.3.1 保存点赞数据到Redis
            stringRedisTemplate.opsForHash().put(user_like_key, user.getId() + "", "1");
            //2.3.2 保存点赞数据到MongoDB
            ApLikesBehavior apLikesBehavior = new ApLikesBehavior();
            apLikesBehavior.setId(ObjectId.get().toHexString());
            apLikesBehavior.setArticleId(dto.getArticleId());
            apLikesBehavior.setType((short) 0);
            apLikesBehavior.setUserId(user.getId());
            apLikesBehavior.setCreatedTime(new Date());

            mongoTemplate.insert(apLikesBehavior);
        }

        //3. 数据返回
        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
    }
}
